package online.lona.mc.bukkit.plugin.ymer;

import online.lona.mc.NativeInterface;
import online.lona.mc.YmerPlayer;
import online.lona.mc.bukkit.plugin.ymer.event.YmerAuthFailedEvent;
import online.lona.mc.bukkit.plugin.ymer.event.YmerAuthTimeoutEvent;
import org.bukkit.entity.Player;

public class StandardYmerPlayer implements YmerPlayer {
    private String playerName;

    public StandardYmerPlayer(Player player) {
        this.playerName = player.getName();
    }

    @Override
    public void onFileAuthenticationFailed() {
        Ymer.Ymer.setPlayerCheckStatus(playerName, false);
        final Player player = Ymer.plugin.getServer().getPlayer(playerName);
        if (player != null && player.isOnline()) {
            YmerAuthFailedEvent event = new YmerAuthFailedEvent(Ymer.Ymer, Ymer.Ymer.getServer().getPlayer(playerName));
            Ymer.Ymer.getServer().getPluginManager().callEvent(event);
            if (!event.isCancelled()) {
                Ymer.plugin.getLogger().info("玩家:" + playerName + " 因验证错误而被踢出服务器");
                player.kickPlayer(Config.getInstance().getAuthFailedMessage());
                Ymer.Ymer.anti_cheat_kick_count++;
            }
        }
    }

    @Override
    public void onFileAuthenticationSuccess() {
        Ymer.Ymer.setPlayerCheckStatus(playerName, true);
    }

    @Override
    public void onFileAuthenticationTimeout() {
        Ymer.Ymer.setPlayerCheckStatus(playerName, false);
        final Player player = Ymer.plugin.getServer().getPlayer(playerName);
        if (player != null && player.isOnline()) {
            YmerAuthTimeoutEvent event = new YmerAuthTimeoutEvent(Ymer.Ymer, Ymer.Ymer.getServer().getPlayer(playerName));
            Ymer.Ymer.getServer().getPluginManager().callEvent(event);
            if (!event.isCancelled()) {
                Ymer.plugin.getLogger().info("玩家:" + playerName + " 因验证超时而被踢出服务器");
                player.kickPlayer(Config.getInstance().getTimeoutMessage());
                Ymer.Ymer.timeout_kick_count++;
            }
        }

    }

    @Override
    public void sendChannelMessage(final byte[] bytes) {
        Ymer.plugin.getServer().getScheduler().runTaskLater(Ymer.plugin, new Runnable() {
            @Override
            public void run() {
                final Player player = Ymer.plugin.getServer().getPlayer(playerName);
                if (player != null && player.isOnline()) {
                    player.sendPluginMessage(Ymer.plugin, NativeInterface.CHANNEL_NAME, bytes);
                }
            }
        }, 1);
    }

    @Override
    public void kick(String reason) {
        final Player player = Ymer.plugin.getServer().getPlayer(playerName);
        player.kickPlayer(reason);
    }

    @Override
    public String getName() {
        return playerName;
    }
}
